package com.users.rn.common.plugin

import android.content.Context
import com.users.rn.common.init.ALHReactNativeInit
import com.users.rn.rncommon.network.utils.SharePreferenceUtils
import com.users.rn.rncommon.plugin.PluginInformation
import java.io.File
import java.lang.Exception

/**

 * 作者：wolf on 1/12/21 11:17

 * 邮箱：bluce

 */

object PluginHelper {


    /**
     * 初始化本地文件
     */
    fun initPlugin(context: Context) {
        parseLocalPluginConfig(context)
        val file: File? = context.getExternalFilesDir("plugin")
        file?.let {
            if (!file.exists()) {
                file.mkdirs()
            }
            PluginInformation.setBasicDir(file.absolutePath)
        }
    }

    private fun parseLocalPluginConfig(context: Context) {
        val oldAppVersion = SharePreferenceUtils.getPreference(context, ParseLocalPlugin.RN_COMMON_PLUGIN_INFO)
                .getLong("appVersion", -1)
        val appVersion = getVersionCode(context)
        if (oldAppVersion < appVersion) { //判断是否已经解析过，如果已经解析过，不需要再解析
            Thread(ParseLocalPlugin(context)).start()
            SharePreferenceUtils.getPreference(context, ParseLocalPlugin.RN_COMMON_PLUGIN_INFO)
                    .edit().putLong("appVersion", appVersion).apply()
        }
    }

    fun savePluginInfo(context: Context, pluginInformation: PluginInformation) {
        val oldVersion = getPluginVersion(pluginInformation.pluginName)
        if (oldVersion < pluginInformation.pluginVersion) {//判断保存的版本比新的版本老，不然就不需要更新
            SharePreferenceUtils.edit(context, pluginInformation.pluginName)
                    .putBoolean(RNPluginFieldKey.PLUGIN_UNPACKING, pluginInformation.isUnpack)
                    .putString(RNPluginFieldKey.MIN_HOST_VERSION, pluginInformation.miniAppVersion.toString())
                    .putString(RNPluginFieldKey.MAX_HOST_VERSION, pluginInformation.maxAppVersion.toString())
                    .putString(RNPluginFieldKey.MD5, pluginInformation.md5)
                    .putString(RNPluginFieldKey.FILE_FULL_PATH, pluginInformation.fullFilePath)
                    .putString(RNPluginFieldKey.FILE_PATH, pluginInformation.filePath)
                    .putLong(RNPluginFieldKey.PLUGIN_VERSION, pluginInformation.pluginVersion)
                    .apply()
        }
    }

    /**
     * 获取插件是否分包
     *
     */
    fun pluginIsPartial(pluginName: String): Boolean {
        return SharePreferenceUtils.getPreference(ALHReactNativeInit.getInitInterface()!!.context, pluginName)
                .getBoolean(RNPluginFieldKey.PLUGIN_UNPACKING, false)!!
    }

    /**
     * 获取插件版本
     */
    fun getPluginVersion(pluginName: String): Long {
        return SharePreferenceUtils.getPreference(ALHReactNativeInit.getInitInterface()!!.context, pluginName)
                .getLong(RNPluginFieldKey.PLUGIN_VERSION, -1)
    }

    /**
     * 判断是可以下载
     */
    fun checkIsLastVersion(pluginInformation: PluginInformation): Boolean {
        val context = ALHReactNativeInit.getInitInterface()!!.context
        val lastPluginVersion = SharePreferenceUtils.getLong(context, pluginInformation.pluginName, RNPluginFieldKey.PLUGIN_VERSION, 0)
        val currentAppVersion = getVersionCode(context)
        if (pluginInformation.pluginVersion > lastPluginVersion && pluginInformation.miniAppVersion <= currentAppVersion) {
            if (pluginInformation.maxAppVersion <= 0 || pluginInformation.maxAppVersion >= currentAppVersion) {
                return true
            }
        }
        return false
    }

    fun getVersionCode(context: Context): Long {
        return try {
            val packageInfo = context.packageManager.getPackageInfo(context.packageName, 0)
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.P) {
                packageInfo.longVersionCode
            } else {
                packageInfo.versionCode.toLong()
            }
        } catch (err: Exception) {
            0
        }
    }

}